# Create your views here.
from django.shortcuts import get_object_or_404, render_to_response
from django.template import Context, loader,RequestContext
from django.http import HttpResponse,HttpResponseRedirect
from myEvents.models import * 
from myEvents.forms  import IndexForm,AdminForm,VoteForm
from django.forms.fields import ChoiceField,MultipleChoiceField

from django.core.mail import EmailMessage
from django.core.context_processors import csrf
from django.views.decorators.csrf import csrf_exempt
import MySQLdb as mdb
import sys
import uuid
import datetime

def enum(**enums):
    return type('Enum', (), enums)
def make_uuid():
    return str(uuid.uuid4().hex)

EVENT_STATUS = enum(INIT=0,VOTING=1,TERMINATED=2)
VOTE_STATUS = enum(NO=0,YES=1,DONTKNOW=2)
  
def getNamebyEmail(email):
    parts = email.strip().split('@')
    return parts[0]

def admin(request,ehash,uhash):
    #restaurants = Place.objects.all();
    restaurants = Place.objects.filter(locality ="Palo Alto");
    e = Event.objects.get(ehash=ehash)
    if int(e.status)==1:
        started=True
    else:
        started=False
    data = {'restaurants':restaurants,'ehash':ehash,'uhash':uhash,'started':started}
    return render_to_response('myEvents/admin.html',data,context_instance=RequestContext(request))

def editEvent(request,ehash,uhash):
    if request.method == "POST":
        form = AdminForm(request.POST or None)
        status = form.is_valid()   #status is valid sometimes and not some times. what the hell...
        status = True;             #left issue to solve! TBD  
        if  status:
            #eventDate = form.cleaned_data.get('eventDate')
            eventDate = request.POST.get('eventDate')
            #voteDate = form.cleaned_data.get('voteDate')
            voteDate = request.POST.get('voteDate')
            #places = form.fields['places'].choices
            places = request.POST.getlist('places')
            emails = request.POST.getlist('emails')    
                 
            place_names = updateEventDB(ehash,uhash,eventDate,voteDate,places,emails)
            request.session['has_created'] = True     # expire the session
            data = {'eventDate': eventDate,'voteDate': voteDate,'places':place_names,'emails':emails}        
            return render_to_response('myEvents/success.html',data,context_instance=RequestContext(request))
        else:
            form = AdminForm()
            return render_to_response('myEvents/error.html',{'adminForm':form},context_instance=RequestContext(request))
    
    return render_to_response('myEvents/admin.html',{'form':form},context_instance=RequestContext(request))
    
 #places: list, emails:list
def updateEventDB(ehash,uhash,eventDate,voteDate,places,emails):
 
    try:
        e = Event.objects.get(ehash=ehash)
        e.eventDate = eventDate
        e.voteDate = voteDate
        e.save()
        #from django.db import connection
        #cursor = connection.cursor()
        #tmp = cursor.execute("UPDATE myEvents_event SET eventDate=%s,voteDate=%s WHERE id = %s", [eventDate,voteDate,e.id])
        #print tmp
        print eventDate,voteDate,e.id
    except Event.DoesNotExist:
        return False   #ehash should be correct. 
    
    place_names = []
    #update event_place table!
    for plid in places:
        p = Place.objects.get(id=plid)
        place_names.append(p.name)
        ep = Event_Place.objects.create(event=e,place=p)
    
    # admin also needs a voting page. 
    url="http://74.95.195.230:8889/myEvents/"+ehash+"/"+uhash+"/attender/"
    u = User.objects.get(uhash=uhash)
    eu = Event_User.objects.create(event=e, user=u,role="attender",url=url)
    voteMail(url,e.name,u.email)
    
    #update participants
    for user_email in emails:
        try:
            u = User.objects.get(email=user_email)
            uhash = u.uhash
        except User.DoesNotExist:
            uhash = make_uuid()
            name = getNamebyEmail(user_email)
            u = User.objects.create(email=user_email,uhash=uhash,name=name)
            #generate url 
        url="http://74.95.195.230:8889/myEvents/"+ehash+"/"+uhash+"/attender/"
        eu = Event_User.objects.create(event=e, user=u,role="attender",url=url)  #update event_user
        voteMail(url,e.name,u.email)
        
    # all mails are sent, update event status
    e.status = EVENT_STATUS.VOTING
    e.save()    
    return place_names  # in order to display names on the success page

def voteMail(url, event_name,send_to):
    subject = "One Event is waiting for your votes! "
    #url_in= "http://192.168.50.201:8888/myEvents/"+e_hash+"/"+u_hash+"/admin/"
    message = "Please Click below URL to vote the event: " + event_name +" \n"+url +\
                "\n If you are in Comcast network, please replace the IP to 192.168.50.201:8888\n"
    email = EmailMessage(subject,message,to=[send_to])
    email.send()
    
    

   